package com.hmkj.web.controller.pay;

import com.hmkj.core.api.ninepai.utils.MerchantConfig;
import com.hmkj.core.api.ninepai.utils.RSASignUtil;
import com.hmkj.core.po.amount.Recharge;
import com.hmkj.core.service.amount.RechargeService;
import com.hmkj.core.service.user.UserBankService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 九派支付异步通知
 *
 * @author Vector
 * @create 2018-01-12 10:18
 */

@Slf4j
@RestController
@RequestMapping(GenericController.BASE_API_URL + "/notify/ninepai")
public class NinePaiPayNotifyController extends GenericController<Integer, Recharge> {

    @Resource
    private UserService userService;

    @Resource
    private UserBankService userBankService;

    @Resource
    private RechargeService rechargeService;


    /**
     * 快捷支付异步通知
     */
    @ResponseBody
    @RequestMapping(value = "/doNotify", method = RequestMethod.POST)
    public void doNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String charset = MerchantConfig.getConfig().getCharset();
        request.setCharacterEncoding("GBK");
        //编码设置
        String encoding = "";
        if ("00".equals(charset)) {
            request.setCharacterEncoding("GB18030");
            encoding = "GB18030";
        } else if ("01".equals(charset)) {
            request.setCharacterEncoding("GB2312");
            encoding = "GB2312";
        } else if ("02".equals(charset)) {
            request.setCharacterEncoding("UTF-8");
            encoding = "UTF-8";
        } else {
            request.setCharacterEncoding("GBK");
            encoding = "GBK";
        }
        try {
            Map<String, String> dataMap = new LinkedHashMap<>();
            dataMap.put("charset", request.getParameter("charset"));
            dataMap.put("version", request.getParameter("version"));
            dataMap.put("acDate", request.getParameter("acDate"));
            dataMap.put("amount", request.getParameter("amount"));
            dataMap.put("bankAbbr", request.getParameter("bankAbbr"));
            dataMap.put("fee", request.getParameter("fee"));
            dataMap.put("memberId", request.getParameter("memberId"));
            dataMap.put("merchantId", request.getParameter("merchantId"));
            dataMap.put("orderId", request.getParameter("orderId"));
            dataMap.put("orderSts", request.getParameter("orderSts"));
            dataMap.put("orderTime", request.getParameter("orderTime"));
            dataMap.put("payTime", request.getParameter("payTime"));
            dataMap.put("payType", request.getParameter("payType"));
            dataMap.put("signType", request.getParameter("signType"));
            dataMap.put("serverSign", request.getParameter("serverSign"));
            dataMap.put("serverCert", request.getParameter("serverCert"));

            Map requestMap = new HashMap();
            requestMap.putAll(dataMap);
            Set set = dataMap.keySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                String tmp = dataMap.get(key);

                if (StringUtils.equals(tmp, "null") || StringUtils.isBlank(tmp)) {
                    requestMap.remove(key);
                    log.info("key:" + key + " ==> value:" + tmp);
                }
            }

            String rootCertPath = MerchantConfig.getConfig().getRootCertPath();

            rootCertPath = "D:\\cert\\rootca.cer";

            //数据签名，hmac为签名后的消息摘要
            RSASignUtil rsautil = new RSASignUtil(rootCertPath);
            String returnData = rsautil.coverMap2String(requestMap);
            log.info("returnData:" + returnData);
            boolean flag = rsautil.verify(returnData, request.getParameter("serverSign"), request.getParameter("serverCert"), encoding);
            if (flag) {
                //验签成功,商户的业务逻辑处理...
                rechargeService.doRechargeBackNinePai(dataMap);
                //处理成功，向平台发送接收到后台通知成功的信息；请执行如下：（注：请不要在out.println其他的信息）
                response.getWriter().println("result=SUCCESS");
                log.info("payAsyncNotify.jsp verify data =========> true");
            } else {
                response.getWriter().println("result=FAILED");
                //验签失败,商户的业务逻辑处理...
                log.info("payAsyncNotify.jsp verify data =========> false");
            }
        } catch (Exception e) {
            log.error("交易异常:" + e.getMessage());
        }
    }


}
